define(["backbone", "_template", "jquery", "_queryConditions", "_cartData", "_base", "_global", "layer_m", "qrcode", "_netPointDialog"],
    function (Backbone, template, $, _qc, _CD, _base, _gl, layer, QRCode, _netPointDialog) {
        return Backbone.View.extend({
            el: '#pageSwitch',
            eventType: "click",
            events: {
                "change #sureAddressInfo": "sureAddressInfo",
                "click #sureAddress": "sureAddress",
                "click #getValidateCode": "getValidateCode",
                "click #sureSweepPay": "surePay",
                "click #openNetPointDialog": "openNetPointDialog",
                "click #paymentWayList a": "paymentWayChoose"
            },
            initialize: function (opts) {

            },
            render: function (opts) {
                var scope = this;
                scope.clearTimer();
                var goodsAllBuy = _CD.getAllBuy();
                var totalPrice = 0;
                for (var i = 0, len = goodsAllBuy.length; i < len; i++) {
                    totalPrice = _base.accAdd(totalPrice, _base.accMul(parseFloat(goodsAllBuy[i].numb), parseFloat(goodsAllBuy[i].price)));
                }
                scope.totalPrice = totalPrice;
                $(scope.el).html(template("templatePay", {
                    totalPrice: totalPrice,
                    phoneLabel: "手机号",
                    isShowOrderWay: true,
                    isShowOrderNote: false,
                    surePayId: "sureSweepPay"
                }));
                scope.loadAddress();
                scope.loadPaymentWay();
                
                _gl.backTop();
            },
            surePay: function (e) {
                var scope = this;
                var $this = $(e.target);
                switch (scope.getPayWay()) {
                    case 6:
                        scope.alipayPay($this);
                        break;
                    case 5:
                        scope.communityPay($this);
                        break;
                    default: break;
                }

            },
            // 支付宝支付
            alipayPay: function (el) {
                var scope = this;
                var $payDialogWrapper = $("#payDialogWrapper");
                var salesmanAccount = $("#salesmanAccount").html();
                var validateCode = $("#validateCode").html();
                if (salesmanAccount.length < 1) {
                    _gl.tips({ content: "手机号码不能为空!", id: "#salesmanAccount" });
                    return false;
                }
                if (validateCode.length < 1) {
                    _gl.tips({ content: "手机验证码不能为空!", id: "#validateCode" });
                    return false;
                }
                if (!salesmanAccount.match(/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/)) {
                    _gl.tips({ content: "您输入的手机号码非法", id: "#salesmanAccount" });
                    return false;
                }
                $(el).prop('disabled', true);
                var url = _gl.getAjaxUrl().orderCreate;
                var post = $.post(url, {
                    mobile: salesmanAccount,
                    pointid: _qc.getNetPoint().id,
                    vcode: validateCode,
                    goods: JSON.stringify(_CD.getAllBuy()),
                    remark: null,
                    payway: scope.getPayWay()
                }, function (data) {
                    if (data.success) {
                        console.log(el)
                        $(el).prop('disabled', false);
                        console.log($(el).prop('disabled'))
                        var orderno = data.result; // 订单号
                        var imgSrc = data.message; // 支付宝扫描二维码base64
                        if (!!imgSrc) {
                            $("#wizard-3").addClass("active");
                            var MaxWait = 180; // 操作间隔最大等待时间
                            var scanWait = MaxWait; // 扫描间隔等待时间
                            scope.buildEWM({
                                MaxWait: MaxWait,
                                imgSrc: imgSrc
                            }); // 生成二维码
                            scope.scanCountdown({
                                MaxWait: MaxWait,
                                scanWait: scanWait,
                                countdown: "#countdown"
                            });// 扫描倒计时
                            // 扫描二维码成功，等待付款倒计时
                            scope.payCountdown({
                                MaxWait: MaxWait,
                                scanWait: scanWait,
                                countdown: "#countdown",
                                orderno: orderno
                            });
                        }
                    }
                    else {
                        _gl.tips({ content: data.message, id: "#validateCode", time: 5 });
                    }
                });
                post.error(function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("OrderCreate error：" + "status=" + XMLHttpRequest.status + " && text=" + textStatus);
                });
            },
            // 信息苑 绿地 支付
            communityPay: function (el) {
                var scope = this;
                var salesmanAccount = $("#salesmanAccount").html();
                var validateCode = $("#validateCode").html();
                var orderInfo = $("#orderInfo").val();
                if (salesmanAccount.length < 1) {
                    _gl.tips({ content: '手机号不能为空！', id: '#salesmanAccount' });
                    return;
                }
                if (validateCode.length < 1) {
                    _gl.tips({ content: '验证码不能为空！', id: '#validateCode' });
                    return;
                }
                if (!salesmanAccount.match(/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/)) {
                    _gl.tips({ content: '您输入的手机号有误！', id: '#salesmanAccount' });
                    return;
                }
                $(el).prop('disabled', true);
                var url = _gl.getAjaxUrl().orderCreate;

                var post = $.post(url, { mobile: salesmanAccount, pointid: _qc.getNetPoint().id, vcode: validateCode, goods: JSON.stringify(_CD.getAllBuy()), remark: orderInfo, payway: scope.getPayWay() }, function (data) {
                    if (data.success) {
                        $(el).prop('disabled', false);
                        var msg = data.message;
                        $("#wizard-3").addClass("active");
                        _CD.delBuy();
                        scope.paySuccess({ info: data.result || '您的订单创建成功' });
                    }
                    else {
                        $(el).prop('disabled', false);
                        _gl.tips({ content: data.message, id: '#validateCode' });
                    }
                });
                post.error(function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("OrderCreate error：" + "status=" + XMLHttpRequest.status + " && text=" + textStatus);
                });
            },
            //创建二维码
            buildEWM: function (opts) {
                var scope = this;
                layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 2,
                    shadeClose: false,
                    skin: 'payDialog',
                    content: template("templateDialogAlipayPay", { totalPrice: scope.totalPrice, MaxWait: opts.time })
                });
                scope.closeDialog();
                var _qrcode = new QRCode("showEWM");
                _qrcode.makeCode(opts.imgSrc);
                $("#showEWM").show().removeAttr("title");
            },
            // 扫描倒计时
            scanCountdown: function (opts) {
                // 扫描二维码付款倒计时
                window.scanCountdownTimer = setInterval(function () {
                    if (opts.scanWait <= 0) {
                        clearInterval(window.scanCountdownTimer);
                        opts.scanWait = opts.MaxWait;
                        $(opts.countdown).html(opts.scanWait);
                        window.location.reload();
                        return;
                    }
                    opts.scanWait--;
                    $(opts.countdown).html(opts.scanWait);
                }, 1000);
            },
            // 付款倒计时
            payCountdown: function (opts) {
                var scope = this;
                var $scanInfo = $("#scanInfo"); // 扫描信息提示
                var payWait = parseInt(opts.MaxWait / 5); // 付款间隔等待时间
                var isResetCountdown = true; // 是否重置倒计时
                // 等待付款时间，不断的请求服务器
                window.payCountdownTimer = setInterval(function () {
                    if (payWait <= 0) {
                        payWait = parseInt(opts.MaxWait / 5);
                        clearInterval(window.payCountdownTimer);
                        return;
                    } else {
                        payWait--;
                        $.post(_gl.getAjaxUrl().OrderStatusQueryAndUpdate, { orderno: opts.orderno, payway: scope.getPayWay() },
                            function (data) {
                                if (data.success) {
                                    if (data.result.toLowerCase() == 'wait') {
                                        if (isResetCountdown) {
                                            opts.scanWait = opts.MaxWait;
                                            payWait = parseInt(opts.MaxWait / 5);
                                            clearInterval(window.scanCountdownTimer); //清除页面操作倒计时，重新计时。
                                            scope.scanCountdown(opts);
                                            isResetCountdown = false;
                                        }
                                        $scanInfo.html("扫码成功！请用手机支付宝完成付款。").addClass("text-danger").show();
                                    }
                                    if (data.result.toLowerCase() == 'success') {
                                        _CD.delBuy();
                                        scope.paySuccess({ info: '恭喜您已经付款成功！' });
                                        clearInterval(window.ewmOrderStatusCountTimer);

                                    }
                                }
                            });
                    }
                }, 5000);
            },
            // 点击关闭按钮，关闭弹窗
            closeDialog: function () {
                var scope = this;
                $(".dialog-closeBtn").off(scope.eventType).on(scope.eventType, function () {
                    scope.closeDialogConfirm();
                });
                $(".laymshade").off(scope.eventType).on(scope.eventType, function () {
                    scope.closeDialogConfirm();
                });
            },
            // 点击layer蒙版，关闭
            closeDialogConfirm: function () {
                var scope = this;
                var layerIndex = _gl.confirm({
                    title: '温馨提示',
                    content: '确定放弃本次付款吗？',
                    btnName: ['确定', '取消'],
                    yes: function () {
                        _gl.close(layerIndex);

                    },
                    no: function () {
                        scope.clearTimer();
                        _gl.closeAll();
                        return false;
                    }
                });

            },
            sureAddressInfo: function () {
                var scope = this;
                var $sureAddressInfo = $("#sureAddressInfo");
                if ($sureAddressInfo.is(":checked")) {
                    $("#dialog-step-1").hide();
                    $sureAddressInfo.hide();
                    $("#dislog-step-2").show();
                    scope.initKeyboardInput();
                    $("#wizard-2").addClass("active");
                }
            },
            // 加载地址
            loadAddress: function () {
                var $payAddress = $('#payAddress');
                $payAddress.text('玩命加载中...');
                //获取网点地址
                var url = _gl.getAjaxUrl().netPointInfo;
                var post = $.post(url, { pointid: _qc.getNetPoint().id }, function (data) {
                    if (data.success) {
                        $payAddress.text(data.result.Address);
                    }
                    else {
                        alert("GetNetPointInfo warning：" + data.message);
                    }
                });
                post.error(function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("GetNetPointInfo error：" + "status=" + XMLHttpRequest.status + " && text=" + textStatus);
                });
            },
            loadPaymentWay: function () {
                var $paymentWay = $('#paymentWayList');
                $paymentWay.html('玩命加载中...');
                //获取网点地址
                var url = _gl.getAjaxUrl().GetPayTypeList;
                var post = $.post(url, { pointid: _qc.getNetPoint().id }, function (data) {
                    if (data.success) {
                        var tHtml = '';
                        if (!!data.result) {
                            $.each(data.result, function (i, item) {
                                tHtml += '<a href="javascript:void(0)" data-type="' + item.Type + '">' + item.Name + '<i></i></a>';
                            });
                            $paymentWay.html(tHtml);
                            // 当只有支付宝支付的时候
                            if (data.result.length == 1) {
                                $("#paymentWayList").attr("data-type", data.result[0].Type).find("a").addClass("active");
                                $("#hideShowSureInfo").attr("data-show", "show").show();
                            }
                        }
                    }
                    else {
                        alert("GetNetPointInfo warning：" + data.message);
                    }
                });
                post.error(function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("GetNetPointInfo error：" + "status=" + XMLHttpRequest.status + " && text=" + textStatus);
                });
            },
            // 确认地址
            sureAddress: function () {
                var $sureAddressInfo = $("#sureAddressInfo");
                if ($("#hideShowSureInfo").attr("data-show") == 'show') {
                    if (!$sureAddressInfo.is(":checked")) {
                        _gl.tips({ content: "请确认地址及信息!", id: "#sureAddressInfo" });
                    }
                }
                if (!$("#paymentWayList").attr("data-type")) {
                    _gl.tips({ content: "请选择支付方式!", id: "#paymentWayList" });
                }
            },
            getValidateCode: function (e) {
                var $this = $(e.target);
                var $salesmanAccount = $("#salesmanAccount");
                var phone = $salesmanAccount.html();
                var mobile = $("#salesmanAccount").html();
                var url = _gl.getAjaxUrl().sendVerifCode;
                if (phone.length < 1) {
                    _gl.tips({ content: "请输入您的手机号", id: "#salesmanAccount" });
                    return false;
                }
                else if (!phone.match(/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/)) {
                    _gl.tips({ content: "您输入的手机号非法", id: "#salesmanAccount" });
                    return false;
                }
                var MAXTIME = 60;
                var maxTime = MAXTIME;
                var tHtml = $this.html();
                window.getValidateCodeTimer = setInterval(function () {
                    if (maxTime <= 0) {
                        clearInterval(window.getValidateCodeTimer);
                        maxTime = MAXTIME
                        $this.html(tHtml);
                        $this.prop("disabled", false);
                    } else {
                        maxTime--;
                        $this.html(maxTime + "秒后再发送");
                        $this.prop("disabled", true);
                    }
                }, 1000);
                var post = $.post(url, { mobile: mobile, opt: 1 }, function (data) {
                    if (data.success) {
                        var msg = data.message;
                    }
                    else {
                        _gl.tips({ content: data.message, id: "#salesmanAccount" });
                        clearInterval(window.getValidateCodeTimer);
                        maxTime = MAXTIME;
                    }
                });
                post.error(function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("SendVerifCode error：" + "status=" + XMLHttpRequest.status + " && text=" + textStatus);
                });
            },
            // 付款成功
            paySuccess: function (d) {
                this.clearTimer();
                _gl.closeAll();
                layer.open({
                    type: 1,
                    title: false,
                    closeBtn: false,
                    shadeClose: false,
                    area: ['550px', '250px'],
                    content: '<div style="padding:30px 30px;text-align:center;">' +
                        '<p style="font-size:18px;padding:30px 0;">' + d.info + '<span style="margin:0 5px;" id="gotoHomeTime">10</span>秒后返回首页。</p>' +
                        '<p><a href="javascript:void(0)" id="goonShoppingBtn"  class="btn btn-danger" style="margin-right:5px;">继续购物</a>' +
                        '<a href="javascript:void(0)" id="stopShoppingBtn"  class="btn btn-danger" style="margin-left:5px;">结束购物</a></p>' +
                        '</div>'
                });
                var maxtimer = 10;
                var $gotoHomeTime = $("#gotoHomeTime");

                var refresh = function () {
                    window.location.href = window.location.href.indexOf("#") > 0 ? window.location.href.split("#")[0] : window.location.href;
                };
                window.gotoHomeTimer = setInterval(function () {
                    if (maxtimer <= 0) {
                        maxtimer = 10;
                        _qc.removeNetPoint();
                        _CD.clear();
                        clearInterval(window.gotoHomeTimer);
                        refresh();
                        return;
                    }
                    maxtimer--;
                    $gotoHomeTime.html(maxtimer);
                }, 1000);
                $("#goonShoppingBtn").off("click").on("click", function () {
                    clearInterval(window.gotoHomeTimer);
                    refresh();
                });
                $("#stopShoppingBtn").off("click").on("click", function () {
                    _qc.removeNetPoint();
                    _CD.clear();
                    clearInterval(window.gotoHomeTimer);
                    refresh();
                });
            },
            clearTimer: function () {
                if (!!window.scanCountdownTimer) {
                    clearInterval(scanCountdownTimer);
                }
                if (!!window.getValidateCodeTimer) {
                    clearInterval(getValidateCodeTimer);
                }
                if (!!window.payCountdownTimer) {
                    clearInterval(window.payCountdownTimer);
                }
                if (!!window.gotoHomeTimer) {
                    clearInterval(window.gotoHomeTimer);
                }
            },
            openNetPointDialog: function () {
                _netPointDialog.init();
            },
            paymentWayChoose: function (e) {
                var scope = this;
                var $this = $(e.target);
                if (e.target.tagName.toLowerCase() == 'i') {
                    $this = $this.parent();
                }
                $("#paymentWayList a").removeClass("active");
                $this.addClass("active");
                $("#paymentWayList").attr("data-type", $this.attr("data-type"));
                $("#hideShowSureInfo").show().attr("data-show", "show");
            },
            getPayWay: function () {
                return parseInt($("#paymentWayList").attr("data-type"));
            },
            initKeyboardInput: function () {
                var self = this;
                $('.m_keyboard_input').off("click").on('click', function () {
                    self.initMKeyboard($(this));
                });
            },
            initMKeyboard: function ($input) {
                var $mk = $('#_m_keyboard_num_container');
                $mk.show();
                var LEN = 10;
                // alert(1)
                var inputX = $input.offset().left;
                var inputY = $input.offset().top;
                var inputW = $input.outerWidth();
                var inputH = $input.height();
                var top, left;
                left = inputX + inputW - $mk.width();
                if (inputY - LEN > $mk.height()) {
                    top = inputY - $mk.height() - LEN;
                } else {
                    top = inputY + inputH + LEN;
                }
                $mk.css({
                    position: 'absolute',
                    left: left,
                    top: top
                });

                $mk.off("touchstart").on("touchstart", "._m_keyboard_item", function (e) {
                    var $this = $(this);
                    $($this).css("background-color", "black");
                })

                $mk.off("touchend").on("touchend", "._m_keyboard_item", function (e) {
                    var $this = $(this);
                    $($this).css("background-color", "rgba(0, 0, 0, 0)");
                })
                
                $(document).on('click', function (e) {
                    if (!$(e.target).hasClass('_m_keyboard_num_el')) {
                        $('#_m_keyboard_num_container').hide();
                    }
                });
                $mk.off("click").on("click", "._m_keyboard_item", function (e) {
                    var $this = $(e.target);
                    var val = $input.html();
                    var key = $this.attr("data-keyboard-key");
                    switch (key) {
                        case "del":
                            if (val.length > 0) {
                                // val.split("").splice(0,val.length-1).join("")
                                $input.html(val.substr(0, val.length - 1));
                            }
                            break;
                        case "clear":
                            $input.html('');
                            break;
                        default:
                            $input.html(val + key);
                            break;
                    }
                });
            }
            
        });
    });